<script setup lang="ts">
import { FormInstance, FormRules } from 'element-plus'
import { login } from '../../api/users'
import { useRouter, useRoute } from 'vue-router'
import { useTokenStore } from '../../stores/mytoken'

const store = useTokenStore()
const router = useRouter()
const route = useRoute()

const form = reactive({
  phone: "19900009439",
  password: ""
})

// 登录事件处理
const onSubmit = async () => {
  isLoading.value = true

  // 验证
  await formRef.value.validate().catch((err) => {
    ElMessage.error('表单校验失败...')
    isLoading.value = false
    throw err
  })

  // 登录
  const data = await login(form).then(res => {
    if (!res.data.success) {
      ElMessage.error("登录信息有误...")
      isLoading.value = false
      throw new Error("登录信息有误...")
    }

    return res.data
  })

  // console.log(data)

  // 保存token
  store.saveToken(data.content)

  isLoading.value = false

  ElMessage.success("登录成功...")

  // 跳转
  router.push(route.query.redirect as string || "/")
}

// 定义是否登录加载中
const isLoading = ref(false)

// 定义表单校验规则
const rules = reactive<FormRules>({
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9\d)\d{8}$/,
      message: '手机号格式不正确',
      trigger: 'blur'
    },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' },
  ],
})

const formRef = ref<FormInstance>()


</script>

<template>
  <div class="login">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="auto" style="max-width: 600px" label-position="top"
      size="large">
      <h2>登录</h2>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" type="password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" :loading="isLoading">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.login {
  background-color: #ddd;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;

  .el-form {
    width: 300px;
    background-color: #f5f1f1;
    padding: 30px;
    border-radius: 10px;

    .el-form-item {
      margin-top: 20px;
    }

    .el-button {
      width: 100%;
      margin-top: 30px;
    }
  }
}
</style>